package cn.itcast.n4_共享模型_管程;

import cn.itcast.util.Sleeper;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

import static cn.itcast.util.Sleeper.sleep;

/**
 * <p>
 * Test39_锁活跃性_解决死锁_但是变成了饥饿
 * </p>
 *
 * @author flyduck
 * @since 2024-10-11
 */
public class Test39_锁活跃性_解决死锁_但是变成了饥饿 {
    public static void main(String[] args) {
        Chopstick2 c1 = new Chopstick2("1");
        Chopstick2 c2 = new Chopstick2("2");
        Chopstick2 c3 = new Chopstick2("3");
        Chopstick2 c4 = new Chopstick2("4");
        Chopstick2 c5 = new Chopstick2("5");
        // 此时都是先拿左边，后拿右边
        new Philosopher2("苏格拉底", c1, c2).start();
        new Philosopher2("柏拉图", c2, c3).start();
        new Philosopher2("亚里士多德", c3, c4).start();
        new Philosopher2("赫拉克利特", c4, c5).start();
        new Philosopher2("阿基米德", c1, c5).start();

        while (true){
            sleep(10);
            System.out.println(Philosopher2.map);//{苏格拉底=3, 赫拉克利特=53, 亚里士多德=26, 柏拉图=8}
        }
    }
}
/**
 * 哲学家类
 */
@Slf4j(topic = "c.Philosopher1")
class Philosopher2 extends Thread {
    public static Map<String,Integer> map = new HashMap<>();
    Chopstick2 left;
    Chopstick2 right;

    public Philosopher2(String name, Chopstick2 left, Chopstick2 right) {
        super(name);
        this.left = left;
        this.right = right;
    }

    @Override
    public void run() {
        while (true) {
            //　尝试获得左手筷子
            synchronized (left) {
                // 尝试获得右手筷子
                synchronized (right) {
                    eat();
                }
                // 放下右手筷子
            }
            //　放下左手筷子
        }
    }

    private void eat() {
        if(!map.containsKey(getName())){
           map.put(getName(), 1);
        }else {
           map.put(getName(), map.get(getName()) + 1);
        }
        log.debug("eating...");
        Sleeper.sleep(0.5);
    }
}

class Chopstick2 {
    String name;

    public Chopstick2(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "筷子{" + name + '}';
    }
}
